package edu.mtu.citizenscience.cs.sdk.uploader.json;

import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import edu.mtu.citizenscience.cs.sdk.uploader.db.UploaderDBInterface;
import edu.mtu.citizenscience.cs.sdk.uploader.json.exception.InvalidRelationship;
import edu.mtu.citizenscience.cs.sdk.uploader.json.exception.InvalidTableName;
import edu.mtu.citizenscience.cs.sdk.uploader.model.Row;

public class DB {
	
	private String name;
	private int version;
	private Table[]	tables;
	
	public void setName(String name)
	{
		this.name = name;
	}
	
	public String getName()
	{
		return this.name;
	}
	
	public void setVersion(int version)
	{
		this.version = version;
	}
	
	public int getVersion()
	{
		return this.version;
	}
	
	public void setTables(Table[] tables)
	{
		this.tables = tables;
	}
	
	public Table[] getTables()
	{
		return this.tables;
	}
	
	@SuppressLint("DefaultLocale")
	public List<Row> getRows(Context context, String mainTableName) throws InvalidTableName, InvalidRelationship
	{
		
		UploaderDBInterface db = new UploaderDBInterface(context, this.name, this.version);
		db.openDB();
		
		for (Table table: this.tables)
		{
			if (table.getName().toUpperCase(Locale.US).equals(mainTableName.toUpperCase(Locale.US)))
			{
				return table.getRows(db, this.tables);
			}
		}
		
		db.closeDB();
		
		throw new InvalidTableName();
	}
	
	public void setUploaded(Context context, List<Row> rows)
	{
		UploaderDBInterface db = new UploaderDBInterface(context, this.name, this.version);
		db.openDB();
		
		for (Row row : rows)
		{
			try 
			{
				ContentValues values = new ContentValues();
				values.put("_UPLOADED", true);
				
				db.getDB().update(row.getTable(), values, "_ID = ?", new String[]{""+row.getId()});
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		
		db.closeDB();
	}

}
